<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { onMounted, onUnmounted, provide } from 'vue'
import io, { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { ref } from 'vue'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import { showToast } from 'vant'
const store = useUserStore()
const route = useRoute()
let socket: Socket
// 消息列表
const list = ref<Message[]>([])
// 订单数据
const consult = ref<ConsultOrderItem>()
provide('consult', consult)
const completeEvaDoc = (score: number) => {
  // 1. 找到未评价的那一条消息
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}

provide('completeEvaDoc', completeEvaDoc)

const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
onMounted(() => {
  loadConsult()
  // 初始化socket
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接
  socket.on('connect', () => {
    console.log('连接成功')
  })
  // 监听断开连接
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
  // 连接异常
  socket.on('error', () => {
    console.log('连接异常')
  })
  // 聊天-查询历史聊天记录
  // 1. 一进入页面 - 默认加载聊天记录
  // 2. 下拉加载 - 执行聊天记录加载
  const initialFlag = ref(true) // 默认是首次加载
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('加载数据')

    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录当前第一条消息大的开始时间
      if (i === 0) time.value = item.createTime
      // console.log(item)
      // 聊天的起始时间
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify, // 通用提示
        createTime: item.createTime,
        msg: {
          content: item.createTime
        }
      })
      // isScroll 是否可以滚动
      // false 不允许滚动到底部
      // true 可以滚动

      /*
        如果是时候首次加载 isScroll true 
      */
      item.items.forEach((v) => (v.isScroll = initialFlag.value === true))
      arr.push(...item.items)
    })
    // 将全部消息变成已读 --> 消息体的最后一条的id
    socket.emit('updateMsgStatus', arr[arr.length - 1].id)
    list.value.unshift(...arr)
    loading.value = false // 关闭loading效果
    if (!data.length) {
      return showToast('没有聊天记录了')
    }

    if (initialFlag.value) {
      // 首次加载
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        // 将默认首次加载的值改成false
        initialFlag.value = false
      })
    }
  })
  // 监听订单状态改变
  socket.on('statusChange', () => loadConsult())
  // 接收消息
  socket.on('receiveChatMsg', async (event) => {
    // 收一条 -> 读一条
    socket.emit('updateMsgStatus', event.id)
    list.value.push(event)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})
onUnmounted(() => {
  socket.close()
})
// 发送文字
const onSendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人 - 自己
    to: consult.value?.docInfo?.id, // 医生
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片
const onSendImage = (image: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人 - 自己
    to: consult.value?.docInfo?.id, // 医生
    msgType: MsgType.MsgImage,
    msg: {
      picture: image
    }
  })
}
// 下拉加载
const loading = ref(false)
const time = ref('')
const onRefresh = () => {
  //向socket服务端发送数据 参数：pageSize: number, lastTime: string, orderId: string
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <!-- navbar -->
    <cp-nav-bar title="问诊室"></cp-nav-bar>
    <!-- 状态栏 -->
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 消息卡片 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></room-message>
    </van-pull-refresh>
    <!-- 操作栏 -->
    <room-action
      @send-text="onSendText"
      @send-image="onSendImage"
      :disabled="consult?.status !== OrderType.ConsultChat"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
